package com.example.ims.fame;

import aj.org.objectweb.asm.commons.JSRInlinerAdapter;
import com.example.ims.pojo.Commodity;
import com.example.ims.pojo.Customer;
import com.example.ims.pojo.SalesOrder;
import com.example.ims.pojo.Supplier;
import com.example.ims.service.CommodityService;
import com.example.ims.service.CustomerService;
import com.example.ims.service.SalesOrderService;
import com.example.ims.service.SupplierService;
import org.hibernate.query.Order;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Component
public class InitFame extends JFrame implements ApplicationListener<ContextRefreshedEvent> {

    public ApplicationContext context;
    private JPanel mainPanel;
    private JButton stockMonitorButton;
    private JButton supplierManagementButton;
    private JButton customerManagementButton;
    private JButton salesOrderManagementButton;
    private CardLayout cardLayout;
    private JPanel cardPanel;

    public CommodityService commodityService;
    private SupplierService supplierService;
    private CustomerService customerService;
    private SalesOrderService salesOrderService;

    public InitFame(ApplicationContext context) {
        this.context=context;
        supplierService=context.getBean(SupplierService.class);
        commodityService=context.getBean(CommodityService.class);
        customerService=context.getBean(CustomerService.class);
        salesOrderService=context.getBean(SalesOrderService.class);
        setTitle("库存管理系统");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        initComponents();
    }

    private void initComponents() {
//        commodityService=context.getBean(CommodityService.class);
        mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        // 模块按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(1, 4));

        stockMonitorButton = new JButton("实时库存监控");
        stockMonitorButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "stockMonitor");
            }
        });
        buttonPanel.add(stockMonitorButton);

        supplierManagementButton = new JButton("供应商管理");
        supplierManagementButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "supplierManagement");
            }
        });
        buttonPanel.add(supplierManagementButton);

        customerManagementButton = new JButton("客户管理");
        customerManagementButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "customerManagement");
            }
        });
        buttonPanel.add(customerManagementButton);

        salesOrderManagementButton = new JButton("销售订单管理");
        salesOrderManagementButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(cardPanel, "salesOrderManagement");
            }
        });
        buttonPanel.add(salesOrderManagementButton);

        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        // 卡片布局面板，用于切换不同模块视图
        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);

        // 实时库存监控面板
        JPanel stockMonitorPanel = createStockMonitorPanel();
        cardPanel.add(stockMonitorPanel, "stockMonitor");

        // 供应商管理面板
        JPanel supplierManagementPanel = createSupplierManagementPanel();
        cardPanel.add(supplierManagementPanel, "supplierManagement");

        // 客户管理面板
        JPanel customerManagementPanel = createCustomerManagementPanel();
        cardPanel.add(customerManagementPanel, "customerManagement");

        // 销售订单管理面板
        JPanel salesOrderManagementPanel = createSalesOrderManagementPanel();
        cardPanel.add(salesOrderManagementPanel, "salesOrderManagement");

        mainPanel.add(cardPanel, BorderLayout.CENTER);

        add(mainPanel);
    }

    private JPanel createStockMonitorPanel() {
        JPanel stockMonitorPanel = new JPanel();
        stockMonitorPanel.setLayout(new BorderLayout());

        // 查询框及相关组件
        JPanel queryPanel = new JPanel();
        JLabel queryLabel = new JLabel("根据商品id查询：");
        JTextField queryTextField = new JTextField(10);
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleQuery(queryTextField.getText());
            }
        });
        queryPanel.add(queryLabel);
        queryPanel.add(queryTextField);
        queryPanel.add(queryButton);
        stockMonitorPanel.add(queryPanel, BorderLayout.NORTH);

        // 库存信息显示区域（使用JScrollPane包裹JTable来实现可滑动查看，此处简单模拟数据展示）
        String[] columnNames = {"商品ID", "商品名称", "库存数量", "规格", "供应商", "地点"};
        List<Commodity> commodityList = commodityService.findAllCommodities();
        Object[][] data = new Object[commodityList.size()][columnNames.length];
        for (int i = 0; i < commodityList.size(); i++) {
            Commodity commodity = commodityList.get(i);
            data[i][0] = commodity.getId();
            data[i][1] = commodity.getName();
            data[i][2] = commodity.getQuantity();
            data[i][3] = commodity.getSize();
            data[i][4] = commodity.getSupplier();
            data[i][5] = commodity.getLocation();
        }
        JTable stockTable = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(stockTable);
        stockMonitorPanel.add(scrollPane, BorderLayout.CENTER);

        // 操作按钮面板
        JPanel operationButtonPanel = new JPanel();
        operationButtonPanel.setLayout(new GridLayout(1, 4));

        // 入库按钮及对应的点击事件处理函数（待实现具体逻辑）
        JButton inStockButton = new JButton("入库");
        inStockButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(context);
//                CommodityRepository commodityRepository=context.getBean(CommodityRepository.class);
//                Commodity commodity=new Commodity();
//                commodity.setName("邓佳铭的智慧");
//                commodity.setSize("100");
//                commodity.setSupplier("崔璨");
//                commodityRepository.save(commodity);
                StockMonitorFame dialog = new StockMonitorFame(stockMonitorPanel,context);
                dialog.setVisible(true);
            }
        });
        operationButtonPanel.add(inStockButton);

        // 出库按钮及对应的点击事件处理函数（待实现具体逻辑）
        JButton outStockButton = new JButton("出库");
        outStockButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleOutStock();
            }
        });
        operationButtonPanel.add(outStockButton);

        JButton inventoryButton = new JButton("盘库");
        inventoryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshStockTable();
            }
        });
        operationButtonPanel.add(inventoryButton);

        // 调拨按钮及对应的点击事件处理函数（待实现具体逻辑）
        JButton transferButton = new JButton("调拨");
        transferButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                int selectedRow = ((JTable) ((JScrollPane) ((JPanel) cardPanel.getComponent(0)).getComponent(1)).getViewport().getView()).getSelectedRow();
                if (selectedRow!= -1) {
                    Long commodityId = (Long) ((JTable) ((JScrollPane) ((JPanel) cardPanel.getComponent(0)).getComponent(1)).getViewport().getView()).getValueAt(selectedRow, 0);
                    TransferFame transferDialog = new TransferFame(InitFame.this, "商品调拨", true, context, commodityId);
                    transferDialog.setVisible(true);
                    refreshStockTable();
                } else {
                    JOptionPane.showMessageDialog(InitFame.this, "请先选择要调拨的商品", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        operationButtonPanel.add(transferButton);

        // 盘点按钮及对应的点击事件处理函数（待实现具体逻辑）


        stockMonitorPanel.add(operationButtonPanel, BorderLayout.SOUTH);

        return stockMonitorPanel;
    }

    // 实时库存监控模块中，根据商品id查询库存信息的函数
    // 功能：接收商品id作为参数，从数据库或其他数据源获取对应商品的库存相关信息，
    //       并将信息更新到界面上的库存信息显示区域（如刷新JTable显示内容）
    private void handleQuery(String productId) {
        if (productId == null || productId.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入有效的商品ID", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }
        try {
            Long id = Long.parseLong(productId);
            // 通过CommodityService根据商品ID查询商品信息
            Optional<Commodity> commodityOptional = commodityService.findById(id);
            if (commodityOptional.isPresent()) {
                Commodity commodity = commodityOptional.get();
                // 获取库存监控面板中的库存信息显示区域（JTable所在的面板）
                JPanel stockMonitorPanel = (JPanel) cardPanel.getComponent(0);
                JScrollPane scrollPane = (JScrollPane) stockMonitorPanel.getComponent(1);
                JTable stockTable = (JTable) scrollPane.getViewport().getView();

                // 定义列名数组，与Commodity类的属性对应（根据实际Commodity类属性调整）
                String[] columnNames = {"商品ID", "商品名称", "库存数量", "规格", "供应商", "地点"};
                Object[][] data = new Object[1][columnNames.length];
                data[0][0] = commodity.getId();
                data[0][1] = commodity.getName();
                data[0][2] = commodity.getQuantity();
                data[0][3] = commodity.getSize();
                data[0][4] = commodity.getSupplier();
                data[0][5] = commodity.getLocation();

                // 创建新的表格模型，将查询到的商品数据设置进去


                DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
                stockTable.setModel(tableModel);
                JOptionPane.showMessageDialog(this, "查询成功", "提示", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "未找到对应商品ID的商品信息", "提示", JOptionPane.WARNING_MESSAGE);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "输入的商品ID格式不正确，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    private void handleOutStock() {
        // 获取当前显示库存信息的JTable
        JTable stockTable = (JTable) ((JScrollPane) ((JPanel) cardPanel.getComponent(0)).getComponent(1)).getViewport().getView();
        int selectedRow = stockTable.getSelectedRow();
        if (selectedRow!= -1) {
            // 获取选中行对应的商品ID（假设商品ID是数据库表的主键，根据实际情况调整获取的列索引）
            Long commodityId = (Long) stockTable.getValueAt(selectedRow, 0);

            try {
                // 通过CommodityService调用数据访问层方法从数据库中删除该商品记录
                Optional<Commodity> commodity=commodityService.findById(commodityId);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date now = new Date();
                String currentTimeStr = sdf.format(now);
                SalesOrder salesOrder=new SalesOrder();
                salesOrder.setOrderType("出库记录");
                salesOrder.setCompletionTime(currentTimeStr);
                salesOrder.setSupplier(commodity.get().getSupplier());
                salesOrderService.addOrder(salesOrder);
                commodityService.deleteCommodityById(commodityId);
                // 刷新界面显示，重新从数据库获取所有商品信息并更新JTable内容
                refreshStockTable();
                JOptionPane.showMessageDialog(this, "商品出库成功", "提示", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "商品出库失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要出库的货物", "提示", JOptionPane.WARNING_MESSAGE);
        }
    }



    private JPanel createSupplierManagementPanel() {
        JPanel supplierManagementPanel = new JPanel();
        supplierManagementPanel.setLayout(new BorderLayout());

        // 查询框及相关组件
        JPanel queryPanel = new JPanel();
        JLabel queryLabel = new JLabel("根据供应商Id查询：");
        JTextField queryTextField = new JTextField(10);
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSupplierQuery(queryTextField.getText());
            }
        });
        queryPanel.add(queryLabel);
        queryPanel.add(queryTextField);
        queryPanel.add(queryButton);
        supplierManagementPanel.add(queryPanel, BorderLayout.NORTH);

        // 供应商信息显示区域（使用JScrollPane包裹JTable来实现可滑动查看）
        String[] columnNames = {"供应商ID", "供应商名称", "联系人", "联系电话", "基本信息", "供货历史", "信用评价"};
        // 从数据库获取供应商数据，通过SupplierService调用相关方法获取所有供应商信息
        List<Supplier> supplierList = supplierService.findAllSuppliers();
        Object[][] data = new Object[supplierList.size()][columnNames.length];
        for (int i = 0; i < supplierList.size(); i++) {
            Supplier supplier = supplierList.get(i);
            data[i][0] = supplier.getId();
            data[i][1] = supplier.getName();
            data[i][2] = supplier.getContact();
            data[i][3] = supplier.getPhone();
            data[i][4] = supplier.getInfo();
            data[i][5] = supplier.getHistory();
            data[i][6] = supplier.getCredit();
        }
        JTable supplierTable = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(supplierTable);
        supplierManagementPanel.add(scrollPane, BorderLayout.CENTER);

        JPanel operationButtonPanel = new JPanel();
        operationButtonPanel.setLayout(new GridLayout(1, 2)); // 根据实际情况调整布局，这里假设只添加一个按钮，设置为 1 行 2 列

        // 添加供应商按钮及对应的点击事件处理函数
        JButton addSupplierButton = new JButton("添加供应商");
        addSupplierButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                AddSupplierFame dialog = new AddSupplierFame(context);
                dialog.setVisible(true);
            }
        });
        operationButtonPanel.add(addSupplierButton);

        JButton deleteSupplierButton = new JButton("删除供应商");
        deleteSupplierButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = supplierTable.getSelectedRow();
                if (selectedRow!= -1) {
                    Long supplierId = (Long) supplierTable.getValueAt(selectedRow, 0);
                    try {
                        // 调用SupplierService的方法删除供应商信息
                        supplierService.deleteSupplierById(supplierId);
                        JOptionPane.showMessageDialog(InitFame.this, "供应商删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        refreshSupplierTable();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(InitFame.this, "供应商删除失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(InitFame.this, "请先选择要删除的供应商", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        operationButtonPanel.add(deleteSupplierButton);

        supplierManagementPanel.add(operationButtonPanel, BorderLayout.SOUTH);

        return supplierManagementPanel;
    }

    // 供应商管理模块中，根据供应商Id查询供应商详细信息的函数
    // 功能：接收供应商Id作为参数，从数据库或存储供应商信息的地方获取对应供应商的详细信息，
    //       包括基本信息、供货历史、信用评价等内容，然后更新界面上供应商信息显示区域（如刷新JTable）
    private void handleSupplierQuery(String supplierId) {
        if (supplierId == null || supplierId.trim().isEmpty()) {
            // 输入框为空，查询所有供应商信息
            refreshSupplierTable();
        } else {
            try {
                Long id = Long.parseLong(supplierId);
                // 根据输入的供应商ID查询供应商信息
                Optional<Supplier> supplierOptional = supplierService.findById(id);
                if (supplierOptional.isPresent()) {
                    Supplier supplier = supplierOptional.get();
                    // 获取库存监控面板中的库存信息显示区域（JTable所在的面板）
                    JPanel stockMonitorPanel = (JPanel) cardPanel.getComponent(1);
                    JScrollPane scrollPane = (JScrollPane) stockMonitorPanel.getComponent(1);
                    JTable stockTable = (JTable) scrollPane.getViewport().getView();

                    // 定义列名数组，与Commodity类的属性对应（根据实际Commodity类属性调整）
                    String[] columnNames = {"供应商ID", "供应商名称", "联系人", "联系电话", "基本信息", "供货历史", "信用评价"};
                    Object[][] data = new Object[1][columnNames.length];
                    data[0][0] = supplier.getId();
                    data[0][1] = supplier.getName();
                    data[0][2] = supplier.getContact();
                    data[0][3] = supplier.getPhone();
                    data[0][4] = supplier.getInfo();
                    data[0][5] = supplier.getHistory();
                    data[0][6] = supplier.getCredit();

                    // 创建新的表格模型，将查询到的商品数据设置进去
                    DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
                    stockTable.setModel(tableModel);
                    JOptionPane.showMessageDialog(this, "查询成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(InitFame.this, "未找到对应供应商ID的供应商信息", "提示", JOptionPane.WARNING_MESSAGE);
                    // 若未找到，可选择重新加载全部供应商信息或者保持当前界面，这里选择重新加载全部供应商信息
                    refreshSupplierTable();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(InitFame.this, "输入的供应商ID格式不正确，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                // 格式错误时，也可选择重新加载全部供应商信息或者保持当前界面，这里选择重新加载全部供应商信息
                refreshSupplierTable();
            }
        }
    }


    private JPanel createCustomerManagementPanel() {
        JPanel customerManagementPanel = new JPanel();
        customerManagementPanel.setLayout(new BorderLayout());

        // 查询框及相关组件
        JPanel queryPanel = new JPanel();
        JLabel queryLabel = new JLabel("根据客户Id查询：");
        JTextField queryTextField = new JTextField(10);
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleCustomerQuery(queryTextField.getText());
            }
        });
        queryPanel.add(queryLabel);
        queryPanel.add(queryTextField);
        queryPanel.add(queryButton);
        customerManagementPanel.add(queryPanel, BorderLayout.NORTH);

        // 客户信息显示区域（使用JScrollPane包裹JTable来实现可滑动查看，此处简单模拟数据展示）
        String[] columnNames = {"客户ID", "客户名称", "联系人", "联系电话", "地址", "信用额度"};
        // 从数据库获取客户数据，通过CustomerService调用相关方法获取所有客户信息
        List<Customer> customerList = customerService.findAllCustomers();
        Object[][] data = new Object[customerList.size()][columnNames.length];
        for (int i = 0; i < customerList.size(); i++) {
            Customer customer = customerList.get(i);
            data[i][0] = customer.getId();
            data[i][1] = customer.getName();
            data[i][2] = customer.getContact();
            data[i][3] = customer.getPhone();
            data[i][4] = customer.getAddress();
            data[i][5] = customer.getCreditLimit();
        }
        JTable customerTable = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(customerTable);
        customerManagementPanel.add(scrollPane, BorderLayout.CENTER);

        JPanel operationButtonPanel = new JPanel();
        operationButtonPanel.setLayout(new GridLayout(1, 3));

        // 添加客户按钮及对应的点击事件处理函数
        JButton addCustomerButton = new JButton("增加客户");
        addCustomerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    // 获取当前的ApplicationContext，假设所在类中有相应获取方法（如之前的代码中从Spring容器获取等方式）
                    // 弹出单独的客户添加界面（假设为AddCustomerFame类，需要创建）
                    AddCustomerFame addCustomerDialog = new AddCustomerFame(InitFame.this, "增加客户", true, context);
                    addCustomerDialog.setVisible(true);
                    // 添加监听器，等待对话框关闭后执行刷新表格操作
                    addCustomerDialog.addWindowListener(new WindowAdapter() {
                        @Override
                        public void windowClosed(WindowEvent windowEvent) {
                            refreshCustomerTable();
                        }
                    });
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(InitFame.this, "打开增加客户界面出现错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        operationButtonPanel.add(addCustomerButton);

        // 删除客户按钮及对应的点击事件处理函数
        JButton deleteCustomerButton = new JButton("删除客户");
        deleteCustomerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = customerTable.getSelectedRow();
                if (selectedRow!= -1) {
                    Long customerId = (Long) customerTable.getValueAt(selectedRow, 0);
                    try {
                        // 调用CustomerService的方法删除客户信息（假设已经有CustomerService和相关方法）
                        customerService.deleteCustomerById(customerId);
                        JOptionPane.showMessageDialog(InitFame.this, "客户删除成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                        refreshCustomerTable();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(InitFame.this, "客户删除失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(InitFame.this, "请先选择要删除的客户", "提示", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        operationButtonPanel.add(deleteCustomerButton);

        customerManagementPanel.add(operationButtonPanel, BorderLayout.SOUTH);

        return customerManagementPanel;
    }

    // 客户管理模块中，根据客户Id查询客户详细信息的函数
    // 功能：接收客户Id作为参数，从数据库或存储客户信息的地方获取对应客户的详细信息，
    //       包括ID、名称、最近购买时间、信用评级等内容，然后更新界面上客户信息显示区域（如刷新JTable）
    private void handleCustomerQuery(String customerId) {
        if (customerId == null || customerId.trim().isEmpty()) {
            // 输入框为空，查询所有供应商信息
            refreshCustomerTable();
        } else {
            try {
                Long id = Long.parseLong(customerId);
                // 根据输入的供应商ID查询供应商信息
                Optional<Customer> customerOptional = customerService.findById(id);
                if (customerOptional.isPresent()) {
                    Customer customer = customerOptional.get();
                    // 获取库存监控面板中的库存信息显示区域（JTable所在的面板）
                    JPanel stockMonitorPanel = (JPanel) cardPanel.getComponent(2);
                    JScrollPane scrollPane = (JScrollPane) stockMonitorPanel.getComponent(1);
                    JTable stockTable = (JTable) scrollPane.getViewport().getView();

                    // 定义列名数组，与Commodity类的属性对应（根据实际Commodity类属性调整）
                    String[] columnNames = {"客户ID", "客户名称", "联系人", "联系电话", "地址", "信用额度"};
                    Object[][] data = new Object[1][columnNames.length];
                    data[0][0] = customer.getId();
                    data[0][1] = customer.getName();
                    data[0][2] = customer.getContact();
                    data[0][3] = customer.getPhone();
                    data[0][4] = customer.getAddress();
                    data[0][5] = customer.getCreditLimit();


                    // 创建新的表格模型，将查询到的商品数据设置进去
                    DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
                    stockTable.setModel(tableModel);
                    JOptionPane.showMessageDialog(this, "查询成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(InitFame.this, "未找到对应客户ID的供应商信息", "提示", JOptionPane.WARNING_MESSAGE);
                    // 若未找到，可选择重新加载全部供应商信息或者保持当前界面，这里选择重新加载全部供应商信息
                    refreshCustomerTable();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(InitFame.this, "输入的供应商ID格式不正确，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                // 格式错误时，也可选择重新加载全部供应商信息或者保持当前界面，这里选择重新加载全部供应商信息
                refreshCustomerTable();
            }
        }
    }

    private JPanel createSalesOrderManagementPanel() {
        JPanel salesOrderManagementPanel = new JPanel();
        salesOrderManagementPanel.setLayout(new BorderLayout());
        // 查询框及相关组件
        JPanel queryPanel = new JPanel();
        JLabel queryLabel = new JLabel("根据订单Id查询：");
        JTextField queryTextField = new JTextField(10);
        JButton queryButton = new JButton("查询");
        queryButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSalesOrderQuery(queryTextField.getText());
            }
        });

        queryPanel.add(queryLabel);
        queryPanel.add(queryTextField);
        queryPanel.add(queryButton);
        salesOrderManagementPanel.add(queryPanel, BorderLayout.NORTH);

        // 客户信息显示区域（使用JScrollPane包裹JTable来实现可滑动查看，此处简单模拟数据展示）
        String[] columnNames = {"订单编号", "订单完成时间", "订单类型", "供货商"};
        // 从数据库获取订单数据，通过SalesOrderService调用相关方法获取所有订单信息
        List<SalesOrder> orderList = salesOrderService.findAllOrders();
        Object[][] data = new Object[orderList.size()][columnNames.length];
        for (int i = 0; i < orderList.size(); i++) {
            SalesOrder order = orderList.get(i);
            data[i][0] = order.getId();
            data[i][1] = order.getCompletionTime();
            data[i][2] = order.getOrderType();
            data[i][3] = order.getSupplier();
        }
        JTable salesOrderTable = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(salesOrderTable);
        salesOrderManagementPanel.add(scrollPane, BorderLayout.CENTER);
        return salesOrderManagementPanel;
    }

    // 销售订单管理模块中，根据订单Id查询订单详细信息的函数
    // 功能：接收订单Id作为参数，从数据库或存储订单信息的地方获取对应订单的详细信息，
    //       包括订单入库时间、出库时间、供货商信息和客户信息等内容，然后更新界面上订单信息显示区域（如刷新JTable）
    private void handleSalesOrderQuery(String orderId) {

        if (orderId == null || orderId.trim().isEmpty()) {
            // 输入框为空，查询所有订单信息
            refreshSalesOrderTable();
        } else {
            try {
                Long id = Long.parseLong(orderId);
                // 根据输入的供应商ID查询供应商信息
                Optional<SalesOrder> salesOrderOptional = Optional.ofNullable(salesOrderService.findById(id));
                if (salesOrderOptional.isPresent()) {
                    SalesOrder salesOrder = salesOrderOptional.get();
                    // 获取库存监控面板中的库存信息显示区域（JTable所在的面板）
                    JPanel stockMonitorPanel = (JPanel) cardPanel.getComponent(3);
                    JScrollPane scrollPane = (JScrollPane) stockMonitorPanel.getComponent(1);
                    JTable stockTable = (JTable) scrollPane.getViewport().getView();

                    // 定义列名数组，与Commodity类的属性对应（根据实际Commodity类属性调整）
                    String[] columnNames = {"订单编号", "订单完成时间", "订单类型", "供货商"};
                    Object[][] data = new Object[1][columnNames.length];
                    data[0][0] = salesOrder.getId();
                    data[0][1] = salesOrder.getCompletionTime();
                    data[0][2] = salesOrder.getOrderType();
                    data[0][3] = salesOrder.getSupplier();

                    // 创建新的表格模型，将查询到的商品数据设置进去
                    DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
                    stockTable.setModel(tableModel);
                    JOptionPane.showMessageDialog(this, "查询成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "未找到对应订单ID的订单信息", "提示", JOptionPane.WARNING_MESSAGE);
                    // 若未找到，可选择重新加载全部订单信息或者保持当前界面，这里选择重新加载全部订单信息
                    refreshSalesOrderTable();
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "输入的订单ID格式不正确，请输入数字", "错误", JOptionPane.ERROR_MESSAGE);
                // 格式错误时，也可选择重新加载全部订单信息或者保持当前界面，这里选择重新加载全部订单信息
                refreshSalesOrderTable();
            }
        }
    }


    private void refreshStockTable() {
        // 获取库存监控面板中的库存信息显示区域（JTable所在的面板）
        JPanel stockMonitorPanel = (JPanel) cardPanel.getComponent(0);
        JScrollPane scrollPane = (JScrollPane) stockMonitorPanel.getComponent(1);
        JTable stockTable = (JTable) scrollPane.getViewport().getView();

        // 获取列名数组，与Commodity类的属性对应（根据实际Commodity类属性调整）
        String[] columnNames = {"商品ID", "商品名称", "库存数量", "规格", "供应商", "地点"};
        // 从数据库获取商品数据，通过CommodityService调用相关方法获取所有商品信息
        List<Commodity> commodityList = commodityService.findAllCommodities();
        Object[][] data = new Object[commodityList.size()][columnNames.length];
        for (int i = 0; i < commodityList.size(); i++) {
            Commodity commodity = commodityList.get(i);
            data[i][0] = commodity.getId();
            data[i][1] = commodity.getName();
            data[i][2] = commodity.getQuantity();
            data[i][3] = commodity.getSize();
            data[i][4] = commodity.getSupplier();
            data[i][5] = commodity.getLocation();
        }

        // 创建新的表格模型，将更新后的数据设置进去
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
        stockTable.setModel(tableModel);
    }

    private void refreshSupplierTable() {
        // 获取供应商管理面板中的供应商信息显示区域（JTable所在的面板）
        JPanel supplierManagementPanel = (JPanel) cardPanel.getComponent(1);
        JScrollPane scrollPane = (JScrollPane) supplierManagementPanel.getComponent(1);
        JTable supplierTable = (JTable) scrollPane.getViewport().getView();

        // 获取列名数组，与Supplier类的属性对应（根据实际Supplier类属性调整）
        String[] columnNames = {"供应商ID", "供应商名称", "联系人", "联系电话", "基本信息", "供货历史", "信用评价"};
        // 从数据库获取供应商数据，通过SupplierService调用相关方法获取所有供应商信息
        List<Supplier> supplierList = supplierService.findAllSuppliers();
        Object[][] data = new Object[supplierList.size()][columnNames.length];
        for (int i = 0; i < supplierList.size(); i++) {
            Supplier supplier = supplierList.get(i);
            data[i][0] = supplier.getId();
            data[i][1] = supplier.getName();
            data[i][2] = supplier.getContact();
            data[i][3] = supplier.getPhone();
            data[i][4] = supplier.getInfo();
            data[i][5] = supplier.getHistory();
            data[i][6] = supplier.getCredit();
        }

        // 创建新的表格模型，将更新后的数据设置进去
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
        supplierTable.setModel(tableModel);
    }

    private void refreshCustomerTable() {
        // 获取客户管理面板中的客户信息显示区域（JTable所在的面板）
        JPanel customerManagementPanel = (JPanel) cardPanel.getComponent(2); // 假设客户管理面板在第三个位置，根据实际情况调整
        JScrollPane scrollPane = (JScrollPane) customerManagementPanel.getComponent(1);
        JTable customerTable = (JTable) scrollPane.getViewport().getView();

        // 获取列名数组，与Customer类的属性对应（根据实际Customer类属性调整）
        String[] columnNames = {"客户ID", "客户名称", "联系人", "联系电话", "地址", "信用额度"};
        // 从数据库获取客户数据，通过CustomerService调用相关方法获取所有客户信息
        List<Customer> customerList = customerService.findAllCustomers();
        Object[][] data = new Object[customerList.size()][columnNames.length];
        for (int i = 0; i < customerList.size(); i++) {
            Customer customer = customerList.get(i);
            data[i][0] = customer.getId();
            data[i][1] = customer.getName();
            data[i][2] = customer.getContact();
            data[i][3] = customer.getPhone();
            data[i][4] = customer.getAddress();
            data[i][5] = customer.getCreditLimit();
        }

        // 创建新的表格模型，将更新后的数据设置进去
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
        customerTable.setModel(tableModel);
    }

    private void refreshSalesOrderTable() {

        // 获取销售订单管理面板中的订单信息显示区域（JTable所在的面板）
        JPanel salesOrderManagementPanel = (JPanel) cardPanel.getComponent(3); // 假设销售订单管理面板在第四个位置，根据实际情况调整
        JScrollPane scrollPane = (JScrollPane) salesOrderManagementPanel.getComponent(1);
        JTable salesOrderTable = (JTable) scrollPane.getViewport().getView();

        // 获取列名数组，与SalesOrder类的属性对应（根据实际SalesOrder类属性调整）
        String[] columnNames = {"订单编号", "订单完成时间", "订单类型", "供货商"};
        // 从数据库获取订单数据，通过SalesOrderService调用相关方法获取所有订单信息
        List<SalesOrder> orderList = salesOrderService.findAllOrders();
        Object[][] data = new Object[orderList.size()][columnNames.length];
        for (int i = 0; i < orderList.size(); i++) {
            SalesOrder order = orderList.get(i);
            data[i][0] = order.getId();
            data[i][1] = order.getCompletionTime();
            data[i][2] = order.getOrderType();
            data[i][3] = order.getSupplier();
        }

        // 创建新的表格模型，将更新后的数据设置进去
        DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
        salesOrderTable.setModel(tableModel);
    }
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        event.getApplicationContext().getParent();
    }

    public void showUI() {
        setVisible(true);
    }
}